package cn.tedu.jdbc;

import java.sql.*;
import java.util.ResourceBundle;

public class JDBCTest08 {
    public static void main(String[] args) {
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            //1.创建链接
            Class.forName(driver);
            //2.获取链接
            conn = DriverManager.getConnection(url, user, password);
            System.out.println("Connection=" + conn);
            //3.获取数据库操作对象
            stmt = conn.createStatement();
            System.out.println("Statement=" + stmt);

            //4.执行SQL语句
            String sql = "insert into t_product(name,price,create_time) values('小米su7urtul',1.0,'2025-05-27')";
            //注意：第二个参数是标志位，用来表示是否将新插入的数据行的主键值返回
            // 执行SQL语句并返回生成的键值
            int count = stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            System.out.println("插入了" + count + "条记录");
            //获取这个新增行的主键值
            //返回的这个rs结果集中就包含了新增行的主键值
            // 获取插入记录后生成的主键值
            rs = stmt.getGeneratedKeys();
            // 检查是否有生成的主键值
            if (rs.next()){
                // 获取生成的主键值
                Long id = rs.getLong(1);
                // 打印新增行的主键值
                System.out.println("新增行的主键值为" + id);
            }


        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            //6.释放资源
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
